package base

import (
	"database/sql/driver"
	"encoding/json"
	"strconv"
)

type DiviMap map[int]float64

func (d DiviMap) Value() (driver.Value, error) {
	b, err := json.Marshal(d)
	return string(b), err
}

func (d *DiviMap) Scan(src interface{}) error {
	return json.Unmarshal(src.([]byte), d)
}

func (d *DiviMap) GetDesc() (desc []DiviDesc, err error) {
	if d == nil {
		return
	}
	ec := GetEmployeeCache()
	desc = make([]DiviDesc, 0, 4)
	var no, name string
	for k, v := range *d {
		no, err = ec.GetNoByID(k)
		if err != nil {
			return
		}
		name, err = ec.GetNameByID(k)
		if err != nil {
			return
		}
		desc = append(desc, DiviDesc{
			EMNO: no,
			EMNM: name,
			DSVL: &v,
		})
	}
	return
}

type DiviType int

const (
	Comp = iota + 1
	IndiSave
	IndiLoan
	BizFee
	IndiClie
)

func (d DiviType) String() string {
	return [...]string{"Comp", "IndiSave", "IndiLoan", "BizFee", "IndiClie"}[d-1]
}

func (d DiviType) EnumIndex() int {
	return int(d)
}

func GetDiviMap(dt DiviType, id int) (diviMap DiviMap, err error) {
	hkey := dt.String() + ":CURR_DIVI:" + strconv.Itoa(id)
	var dMap map[string]string
	dMap, err = RedisCli.HGetAll(rctx, hkey).Result()
	if err != nil {
		return
	}
	diviMap = make(DiviMap, 6)
	for k, v := range dMap {
		if v == "0" {
			continue
		}
		key, _ := strconv.Atoi(k)
		val, _ := strconv.ParseFloat(v, 64)
		diviMap[key] = val
	}
	return
}

func SetDiviMap(dt DiviType, id int, divis ...interface{}) (err error) {
	hkey := dt.String() + ":CURR_DIVI:" + strconv.Itoa(id)
	err = RedisCli.Del(rctx, hkey).Err()
	if err != nil {
		return
	}
	err = RedisCli.HMSet(rctx, hkey, divis).Err()
	return
}

type DiviDesc struct {
	EMNO string   `json:"EMNO"`
	EMNM string   `json:"EMNM"`
	DSVL *float64 `json:"DSVL"`
}
